import 'package:bai_le_men_im/cmomon/utils.dart';
import 'package:bai_le_men_im/pages/addFriends.dart';
import 'package:flutter/material.dart';
import 'package:flutter_wildfire/flutter_wildfire.dart';
import '../cmomon/usersModel.dart';
import '../models/index.dart';
import 'package:provider/provider.dart';

class FriendRequestPage extends StatefulWidget {
  @override
  _FriendRequestPageState createState() => _FriendRequestPageState();
}

class _FriendRequestPageState extends State<FriendRequestPage> {
  List requestList = [];

  getRequestList() async {
    var result = await FlutterWildfire.getFriendRequest(true);
    print(result);
    requestList.addAll(List.generate(result.length, (i) => result[i]));
    this.setState(() {});
    // [{direction: 0, readStatus: 0, reason: 我是 15367680315, status: 0, target: AOAsAszz, timestamp: 508494509}]
  }

  clearUnreadFriendRequest () async{
    await FlutterWildfire.clearUnreadFriendRequestStatus();
  }

  @override
  void initState() {
    getRequestList();
    clearUnreadFriendRequest();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('新的朋友'),
        actions: <Widget>[
          MaterialButton(
            color: Colors.green,
            // textColor: Colors.white,
            child: Text('添加'),
            padding: EdgeInsets.all(0.0),
            onPressed: () {
              Navigator.of(context)
                  .push(new MaterialPageRoute(builder: (context) {
                return AddFriendPage();
              }));
            },
          )
        ],
      ),
      body: ListView.separated(
        itemCount: requestList.length,
        separatorBuilder: (BuildContext context, int index) => Divider(),
        itemBuilder: (BuildContext context, int index) {
          var item = requestList[index];
          // {direction: 0, readStatus: 0, reason: 我是 15367680315, status: 0, target: AOAsAszz, timestamp: 508494509}
          // print();
          return RequestItem(
              userId: item['target'],
              reason: item['reason'],
              status: item['status']);
        },
      ),
    );
  }
}

class RequestItem extends StatefulWidget {
  final String reason;
  final String userId;
  final int status;

  RequestItem({@required this.userId, this.reason, this.status});
  @override
  _RequestItemState createState() => _RequestItemState();
}

class _RequestItemState extends State<RequestItem> {
  bool showApprovalBtn = false;
  @override
  void didChangeDependencies() {
    showApprovalBtn = (widget.status == 0);
    super.didChangeDependencies();
  }

  // targetUser = await Provider.of<UsersModel>(context, listen: false)
  //     .getUserInfoById(otherSideUserId);
  @override
  Widget build(BuildContext context) {
    return FutureBuilder<User>(
        future: Provider.of<UsersModel>(context, listen: false)
            .getUserInfoById(widget.userId),
        builder: (BuildContext context, AsyncSnapshot<User> snapshot) {
          String avatarUrl;
          String displayName = widget.userId;
          if (snapshot.hasData) {
            User user = snapshot.data;
            avatarUrl = user.portrait;
            displayName = user.displayName;
          }
          Widget avatar = myAvatar(avatarUrl);
          Widget trailingWidget;
          if (showApprovalBtn) {
            trailingWidget = FlatButton(
              padding: EdgeInsets.all(0.0),
              color: Colors.green,
              onPressed: () async {
                var result = await showDialog(
                    context: context,
                    builder: (context) {
                      return new AlertDialog(
                        title: new Text("接受好友请求？"),
                        // content: ,
                        actions: <Widget>[
                          new FlatButton(
                            onPressed: () async {
                              try {
                                await FlutterWildfire.handleFriendRequest(
                                    widget.userId, true);
                                Navigator.pop(context, true);
                              } catch (e) {
                                print('handleFriendRequest error');
                                Navigator.pop(context, false);
                              }
                            },
                            child: new Text("确认"),
                          ),
                          new FlatButton(
                            onPressed: () {
                              Navigator.of(context).pop();
                            },
                            child: new Text("取消"),
                          ),
                        ],
                      );
                    });
                print('result');
                print(result);
                if (result == false) {
                  Scaffold.of(context).showSnackBar(SnackBar(
                      content: Text('操作失败'),
                      // action: SnackBarAction(label: '撤销', onPressed: decrease),
                      duration: Duration(milliseconds: 1000)));
                }
                if (result) {
                  this.setState(() {
                    showApprovalBtn = false;
                  });
                }
              },
              child: Text(
                '接受',
                style: TextStyle(color: Colors.white),
              ),
            );
          } else {
            trailingWidget = Text('已接受');
          }
          return ListTile(
            trailing: trailingWidget,
            leading: avatar,
            subtitle: Text(widget.reason),
            title: Text(
              displayName,
              style: TextStyle(),
            ),
          );
        });
  }
}
